<template>
  <div class="edit-info-container">
    <div class="edit-info-card">
      <h2 class="edit-info-title">编辑个人信息</h2>
      
      <el-form 
        label-position="top" 
        class="edit-info-form"
        :model="userInfo"
        ref="editForm"
      >
        <!-- 头像上传 -->
        <el-form-item label="头像">
          <div class="avatar-upload">
            <div class="avatar-wrapper">
              <el-avatar 
                :size="80" 
                :src="avatarUrl"
                class="avatar-img"
              >
                {{ usernameFirstChar }}
              </el-avatar>
              <el-button 
                type="primary" 
                size="small" 
                class="upload-btn"
                @click="handleAvatarUpload"
              >
                更换头像
              </el-button>
              <input 
                type="file" 
                ref="fileInput" 
                accept="image/*" 
                style="display: none"
                @change="onFileChange"
              />
            </div>
          </div>
        </el-form-item>
        
        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input 
            placeholder="设置您的用户名（3-20个字符）" 
            size="large"
            class="custom-input"
            v-model="userInfo.full_name"
            :disabled="true"
          />
        </el-form-item>
        
        <!-- Email 输入 -->
        <el-form-item label="邮箱">
          <el-input 
            placeholder="请输入您的邮箱地址" 
            size="large"
            class="custom-input"
            v-model="userInfo.email"
            :disabled="true"
          />
        </el-form-item>
        
        <!-- 当前密码 -->
        <div class="password-container">
          <label class="password-label">当前密码</label>
          <el-input 
            type="password"
            class="custom-input"
            placeholder="请输入当前密码"
            v-model="passwordForm.currentPassword"
             show-password
          />
        </div>
        
        <!-- 新密码 -->
        <div class="password-container">
          <label class="password-label">新密码</label>
          <el-input 
            type="password"
            class="custom-input"
            placeholder="设置8-20位密码（字母+数字）"
            v-model="passwordForm.newPassword"
             show-password
          />
        </div>
        
        <!-- 确认新密码 -->
        <div class="password-container">
          <label class="password-label">确认新密码</label>
          <el-input 
            type="password"
            class="custom-input"
            placeholder="请再次输入新密码"
            v-model="passwordForm.confirmPassword"
             show-password
          />
        </div>
        
        <!-- 保存按钮 -->
        <el-button 
          type="primary" 
          size="large" 
          class="save-btn"
          @click="handleSave"
          :loading="loading"
        >
          保存修改
        </el-button>
        
        <!-- 返回链接 -->
        <div class="back-link">
          <el-link type="primary" @click="goBack">返回个人中心</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { userApi } from '@/utils/api'
import apiConfig from '../utils/apiConfig'

export default {
  name: 'EditInfo',
  data() {
    return {
      userInfo: {
        email: '',
        full_name: '',
        avatar_url: ''
      },
      passwordForm: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      loading: false,
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
  },
  computed: {
    usernameFirstChar() {
      return this.userInfo.full_name ? this.userInfo.full_name.charAt(0).toUpperCase() : 'U'
    },
    avatarUrl() {
      // 如果用户有头像URL，则使用该URL，否则使用默认头像
      if (this.userInfo.avatar_url) {
        // 如果是绝对URL直接使用，否则加上基础路径
        if (this.userInfo.avatar_url.startsWith('http')) {
          return this.userInfo.avatar_url;
        } else {
            // 否则加上基础URL
            const baseUrl = apiConfig.imageBaseURL.development;
            console.log('baseUrl:', baseUrl)
            // 处理路径中的重复斜杠
            if (this.userInfo.avatar_url.startsWith('/')) {
               return baseUrl + this.userInfo.avatar_url;
            } else {
               return baseUrl + '/' + this.userInfo.avatar_url;
            }
        }
      }
      return this.defaultAvatar;
    }
  },
  mounted() {
    this.loadUserInfo()
  },
  methods: {
    async loadUserInfo() {
      try {
        const response = await userApi.getUserInfo()
       
        this.userInfo = {
          ...this.userInfo,
          ...response
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
      }
    },
    
    handleAvatarUpload() {
      this.$refs.fileInput.click()
    },
    
    onFileChange(e) {
      const file = e.target.files[0]
      if (file) {
        // 实际上传头像到服务器
        this.uploadAvatar(file)
      }
    },
    
    async uploadAvatar(file) {
      const formData = new FormData()
      formData.append('file', file)
      
      try {
        const response = await userApi.uploadAvatar(formData)
        console.log('头像上传成功:', response)
        // 更新用户信息中的头像URL
        this.userInfo.avatar_url = response.avatar_url || response.data?.avatar_url
        this.$message.success('头像上传成功')
      } catch (error) {
        console.error('头像上传失败:', error)
        this.$message.error('头像上传失败，请重试')
      }
    },
    
 
    async handleSave() {
      // 验证密码修改
      if (this.passwordForm.newPassword || this.passwordForm.confirmPassword) {
        if (!this.passwordForm.currentPassword) {
          this.$message.error('请输入当前密码')
          return
        }
        
        if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
          this.$message.error('新密码与确认密码不一致')
          return
        }
        
        if (this.passwordForm.newPassword.length < 8) {
          this.$message.error('新密码至少8位字符')
          return
        }
      }
      
      this.loading = true
      
      try {
        // 如果有新密码，先修改密码
        if (this.passwordForm.newPassword) {
          const passwordData = {
            current_password: this.passwordForm.currentPassword,
            new_password: this.passwordForm.newPassword
          };
          
          await userApi.changePassword(passwordData);
        }
        
        this.$message.success('信息保存成功')
        this.$router.push('/personal-center')
      } catch (error) {
        console.error('保存失败:', error)
        if (error.response && error.response.data && error.response.data.detail) {
          this.$message.error(error.response.data.detail)
        } else {
          this.$message.error('保存失败，请重试')
        }
      } finally {
        this.loading = false
      }
    },
// ... existing code ...
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.edit-info-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: calc(100vh - 100px);
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 50px;
}

.edit-info-card {
  width: 100%;
  max-width: 500px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.edit-info-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.edit-info-form {
  width: 100%;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.avatar-img {
  margin-bottom: 10px;
}

.upload-btn {
  margin-top: 10px;
  width: 100px;
  padding: 8px 16px;
  font-size: 12px;
}

.password-container {
  margin-bottom: 20px;
}

.password-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.custom-input {
  width: 100%;
}

.save-btn {
  width: 100%;
  margin-top: 20px;
}

.back-link {
  text-align: center;
  margin-top: 20px;
}
</style>